package com.automation.scripts.common.util.appium;

import io.appium.java_client.android.AndroidDriver;
import lombok.AllArgsConstructor;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@AllArgsConstructor
public class AndroidAppiumOperator implements IAppiumOperator {
    private final AndroidDriver driver;

    @Override
    public WebElement waitFor(By locator, Duration timeout) {
        WebDriverWait wait = new WebDriverWait(this.driver, timeout);
        return wait.until(d -> {
            try {
                WebElement element = d.findElement(locator);
                if (element.isDisplayed()) {
                    System.out.printf("找到组件 %s\n", locator);
                    return element;
                }
            } catch (Exception e) {
                System.out.printf("找不到组件 %s\n", locator);
            }
            return null;
        });
    }

    @Override
    public WebElement waitForOne(List<By> locators, Duration timeout) {
        WebDriverWait wait = new WebDriverWait(this.driver, timeout);
        return wait.until(d -> {
            for (By locator : locators) {
                try {
                    WebElement element = d.findElement(locator);
                    if (element.isDisplayed()) {
                        System.out.printf("找到组件 %s\n", locator);
                        return element; // 找到第一个可见的直接返回
                    }
                } catch (Exception e) {
                    System.out.printf("找不到组件 %s\n", locator);
                }
            }
            return null;
        });
    }

    @Override
    public List<WebElement> waitForAll(List<By> locators, Duration timeout) throws Exception {
        WebDriverWait wait = new WebDriverWait(this.driver, timeout);
        List<WebElement> elements = new ArrayList<>(Collections.nCopies(locators.size(), null));
        return wait.until(d -> {
            for (int i = 0; i < locators.size(); i++) {
                if (elements.get(i) != null) continue;
                By locator = locators.get(i);
                try {
                    WebElement element = d.findElement(locator);
                    if (element.isDisplayed()) {
                        System.out.printf("找到组件 %s\n", locator);
                        elements.set(i, element);
                    }
                } catch (Exception e) {
                    System.out.printf("找不到组件 %s\n", locator);
                }
            }
            for (WebElement element : elements) {
                if (element == null) return null;
            }
            return elements;
        });
    }

    @Override
    public void quit() {
        if (this.driver != null) this.driver.quit();
    }
}
